using Admin2025.Domain.Entities.App;
using Admin2025.Domain.Repositories;

namespace Admin2025.Application.Services;

public class AuthService
{
  private readonly IRepository<AppUser> _userRepo;
  private readonly IRepository<AppRole> _roleRepo;

  public AuthService(IRepository<AppUser> userRepo, IRepository<AppRole> roleRepo)
  {
    _userRepo = userRepo;
    _roleRepo = roleRepo;
  }

  // 注册功能
  public async Task RegisterAsync(string username, string password)
  {
    // 1. 检查用户名是否存在
    var exists = (await _userRepo.GetAllAsync()).Any(u => u.Username == username);
    if (exists) throw new Exception("用户名已存在");

    // 2. 生成盐和加密密码
    var salt = Guid.NewGuid().ToString("N");
    var hashedPwd = HashPassword(password, salt);

    // 3. 分配默认角色
    var defaultRole = (await _roleRepo.GetAllAsync()).FirstOrDefault(r => r.RoleName == "User");
    var user = new AppUser
    {
      Username = username,
      Password = hashedPwd,
      Salt = salt
    };
    if (defaultRole != null)
      user.AssignRole(defaultRole);

    // 4. 保存
    await _userRepo.CreateAsync(user);
  }

  // 登录功能
  public async Task<AppUser?> LoginAsync(string username, string password)
  {
    var user = (await _userRepo.GetAllAsync()).FirstOrDefault(u => u.Username == username);
    if (user == null) return null;

    var hashedPwd = HashPassword(password, user.Salt);
    if (user.Password != hashedPwd) return null;

    return user;
  }

  private string HashPassword(string password, string salt)
  {
    // 简单示例，实际请用更安全的哈希算法
    using var sha256 = System.Security.Cryptography.SHA256.Create();
    var bytes = System.Text.Encoding.UTF8.GetBytes(password + salt);
    var hash = sha256.ComputeHash(bytes);
    return Convert.ToBase64String(hash);
  }
}